<template>
  <div class="pageOut">
    <div class="pageIn">
      <el-form :inline="true" :model="formSearch" size="small">
        <el-form-item>
          <el-input
            v-model="formSearch.menu_name"
            placeholder="Banner名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            value-format="yyyy-MM-dd"
            v-model="formSearch.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" @click="search">查询</el-button>

          <el-button
            icon="el-icon-plus"
            type="primary"
            v-if="permission.add"
            @click="handleAdd"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        border
        ref="table"
        :height="height - 270"
        :data="tableData"
        :header-cell-style="{ background: '#FAFAFA', color: '#606266' }"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        style="width: 100%"
      >
        <el-table-column prop="bannerName" :show-overflow-tooltip="tooltip" label="Banner名称"></el-table-column>
        <el-table-column prop="sort" label="排序"></el-table-column>
        <el-table-column prop="typeName" label="Banner类型"></el-table-column>
        <el-table-column label="关联链接">
          <template slot-scope="scope">
            <el-link type="primary" @click="deliClick(scope.row)"
              >点击查看</el-link
            >
          </template>
        </el-table-column>

        <el-table-column prop="mainPicture" label="Banner图片" align="center">
          <template slot-scope="scope">
            <div class="img" style="cursor: pointer">
              <viewer>
                <img
                  :src="scope.row.mainPicture"
                  alt
                  :onerror="errImg"
                  title="查看高清图片"
                  style="width: 40px; height: 40px; border-radius: 50%"
                />
              </viewer>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="添加时间"></el-table-column>

        <el-table-column label="操作" width="320" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row)"
              v-show="permission.edit"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row.id)"
              v-show="permission.del"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>

      <!-- 商品添加和商品编辑 -->
      <el-dialog
        :title="type === 'add' ? '添加商品' : '修改商品'"
        :visible.sync="visible"
        width="40%"
        @close="onCancel('ruleForm')"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          size="mini"
          label-width="110px"
          class="form-drawer__main"
        >
          <el-form-item
            label="名称"
            prop="menu_name"
            style="margin-bottom: 30px"
          >
            <el-input
              class="formInput"
              clearable
              v-model="ruleForm.menu_name"
              placeholder="请输入名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="排序"
            prop="inventory"
          maxlength="5"
            style="margin-bottom: 30px"
          >
            <el-input
              placeholder="请输入排序"
              class="formInput"
              v-model="ruleForm.inventory"
              oninput="this.value=this.value.replace(/[^\d]/g,'')"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="Banner类型"
            prop="cate_id"
            style="margin-bottom: 30px"
          >
            <el-select disabled v-model="ruleForm.cate_id" placeholder="请选择">
              <el-option
                v-for="item in bannerType"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="关联链接">
            <div class="display:flex">
              <el-button size="mini" v-if="ruleForm.cate_id == 2" type="primary"
                >选择活动</el-button
              >
              <el-button size="mini" @click="clickDevic" v-else type="primary"
                >选择商品</el-button
              >
            </div>
          </el-form-item>
          <div style="margin-bottom: 10px; margin-left: 110px">
            <el-tag
              v-for="(tag, tagIndex) in goodsRow"
              @close="closeTag(tagIndex, tag)"
              :key="tagIndex"
              closable
              style="margin-right: 10px"
            >
              {{ tag.name }}
            </el-tag>
          </div>
          <el-form-item
            label="Banner图"
            prop="menu_image"
            style="margin-bottom: 30px"
          >
            <UploadImage
              @getImgSrc="getImgSrc"
              :imageUrl.sync="ruleForm.menu_image"
              ref="image"
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="onCancel('ruleForm')" size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="onConfirm('ruleForm')"
            :loading="confirmLoading"
            >{{ confirmLoading ? "提交中 ..." : "确 定" }}</el-button
          >
        </span>
      </el-dialog>

      <el-dialog title="选择产品"  :visible.sync="goodsDialog" width="35%">
        <el-form :inline="true" :model="dialogSearch" size="small">
          <el-form-item>
            <el-cascader
              v-model="dialogSearch.merchant_id"
              :props="casProps"
              :options="casOptions"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="dialogSearch.name"
              placeholder="商品名称"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button icon="el-icon-search" @click="getGoodsSel"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          ref="multipleTable"
          :data="cleckData"
          tooltip-effect="dark"
          style="width: 100%"
          @select-all="selectAll"
          height="450"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>

          <el-table-column label="图片">
            <template slot-scope="scope">
              <img
                :src="scope.row.mainPicture"
                style="width: 40px"
                height="40px"
                alt=""
              />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="sellingPrice"
            label="价格"
            show-overflow-tooltip
          >
          </el-table-column>
        </el-table>
        <!-- <div class="pageBox">
          <el-pagination
            @current-change="dailogHandleSizeChange"
            background
            layout="prev, pager, next"
            :total="dialogTotal"
          >
          </el-pagination>
        </div> -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="goodsDialog = false">取 消</el-button>
          <el-button type="primary" @click="goodsDialog = false"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  bannerList,
  bannerDel,
  bannerAdd,
  bannerEdit,
  goodsDetail,
  allGoods,
  MAIN,
  saleUpdate,
  typeList,
  goodsSel,
} from "../../utils/api";
import UploadImage from "../../components/UploadImage";
import UploadImg from "../../components/UploadImg";
import Editor from "../../components/Editor";
export default {
  name: "Taste",
  props: ["height"],
  components: {
    UploadImg,
    UploadImage,
    Editor,
  },
  data() {
    return {
      dialogTotal: 0,
      goodsDialog: false,
      options: {
        type: "picture-card",
        limit: 5,
      }, //上传图片配置项
      goodsRow: [],

      casOptions: [],
      casProps: {
        value: "id",
        label: "name",
        children: "child",
      },
      tableData: [
        {
          id: 1,
        },
      ],
      cleckData: [],
      tooltip: true, //内容过长被隐藏时显示 tooltip
      loading: true, //显示加载表格
      pageSize: 10, //每页多少条
      currentPage: 1, //当前第几页
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //共多少条
      permission: {
        add: false,
        edit: false,
        del: false,
      }, //权限
      errImg: 'this.src="' + require("../../../static/img/user.png") + '"',
      formSearch: {
        merchant_id: "",
        menu_name: "",
        priceMin: "",
        priceMax: "",
        time: "",
      }, //搜索
      userinfo: {},
      casOptions: [],
      doaPageNumber: 1,
      casProps: {
        value: "id",
        label: "name",
        children: "child",
      },
      bannerType: [
        {
          id: 1,
          name: "商品",
        },
        {
          id: 2,
          name: "活动",
        },
      ],
      //编辑弹窗
      visible: false,
      confirmLoading: false,
      type: "",
      currentRow: {}, //当前行数据信息
      ruleForm: {
        menu_name: "",
        menu_price: "",
        menu_image: "",
        is_show: 1,
        inventory: "",
        cate_id: 1,
        menu_content: "",
        rotation_images: "", //轮播图片列表 商品
        detail_images: [], //详情图片列表 商品
      }, //添加和修改的表单
      dialogSearch: {
        name: "",
        merchant_id: "",
      },
      rules: {
        menu_content: [
          { required: true, message: "请选择链接", trigger: "blur" },
        ],
        menu_name: [{ required: true, message: "请输入名称", trigger: "blur" }],

        menu_image: [
          { required: true, message: "请上传图片", trigger: "change" },
        ],

        inventory: [{ required: true, message: "不能为空", trigger: "blur" }],
        cate_id: [{ required: true, message: "请选择分类", trigger: "change" }],
      },
      merchant: {}, //商家列表
      cate: {}, //商品分类列表
    };
  },

  mounted() {
    this.getResource();

    this.cateSelects(); //商品分类列表
    this.getGoodsSel();
  },
  methods: {
    deliClick(row) {
      this.$router.push({
        name: "GoodsList",
        query: {
          goodsId: row.objectId,
        },
      });
    },
    selectAll() {},
    getGoodsSel() {
      let params = {
        name: this.dialogSearch.name,
        goodsTypeTwo: this.dialogSearch.merchant_id[1] || "",
        pageSize: 1000,
        pageNumber: this.doaPageNumber,
      };
      this.postRequest(goodsSel, params, MAIN).then((res) => {
        if (res.code === 200) {
          this.cleckData = res.data.list;
          this.dialogTotal = res.data.count;
        }
      });
    },
    dailogHandleSizeChange(val) {
      this.doaPageNumber = val;
      this.getGoodsSel();
    },
    //富文本框
    onEditorChange(e) {
      this.ruleForm.rotation_images = e;
    },
    casHandleChange() {},
    // 商品分类列表
    cateSelects() {
      this.postRequest(typeList, MAIN).then((res) => {
        if (res.code == 200) {
          this.casOptions = res.data;
        }
      });
    },
    // 商品标签删除
    closeTag(index, item) {
      this.goodsRow.splice(index, 1);
      this.$refs.multipleTable.toggleRowSelection(item, false);
    },
    handleSelectionChange(selection) {
      this.goodsRow = selection;
      if (selection.length > 1) {
        let del_row = selection.shift();
        this.$refs.multipleTable.toggleRowSelection(del_row, false);
      }
      console.log(this.goodsRow);
    },
    //获取权限资源
    getResource() {
      // console.log(this.$route.name);
      this.loading = true;
      const userinfo = JSON.parse(sessionStorage.getItem("userInfo")); //解密,获取用户登录信息
      this.userinfo = userinfo;
      let arr = userinfo.menu_id.split(",");
      // console.log(arr)
      // 新增 108
      // 修改 109
      // 删除 110

      if (arr.indexOf("108") > -1) {
        this.permission.add = true;
      }
      if (arr.indexOf("109") > -1) {
        this.permission.edit = true;
      }

      if (arr.indexOf("110") > -1) {
        this.permission.del = true;
      }

      this.getData();
      this.merchantSelects(); //商家下拉列表
    },
    //清除输入框负数
    clearMinus(e, type) {
      let boolean = new RegExp("^[0-9][0-9.]*$").test(e.target.value);
      if (!boolean) {
        e.target.value = "";
        if (type === "menu_price") this.ruleForm.menu_price = "";
        if (type === "menu_money") this.ruleForm.menu_money = "";
      }
    },
    //   商家下拉列表
    merchantSelects() {
      this.postRequest(allGoods, {}, MAIN).then((res) => {
        if (res.code == 200) {
          this.merchant = res.data;
        }
      });
    },

    // 商品分类列表
    cateSelects() {
      this.postRequest(typeList, MAIN).then((res) => {
        if (res.code == 200) {
          this.casOptions = res.data;
        }
      });
    },
    // 商品主图
    getImgSrc(e) {
      this.ruleForm.menu_image = e;
    },
    // 轮播图
    getImgSrc2(e) {
      this.ruleForm.rotation_images = e;
    },
    // 详情图
    getImgSrc3(e) {
      this.ruleForm.detail_images = e;
      console.log(e);
    },
    //获取初始数据
    getData() {
      this.loading = true;
      let start_time, end_time;
      if (this.formSearch.time != "" && this.formSearch.time != null) {
        start_time = this.formSearch.time[0];
        end_time = this.formSearch.time[1];
      }
      let params = {
        userId: this.userinfo.id,
        bannerName: this.formSearch.menu_name,
        usageType: 2,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
        start_time,
        end_time
      };
      this.postRequest(bannerList, params, MAIN).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.count;
          this.loading = false;
          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.table) this.$refs.table.doLayout();
          });
        }
      });
    },

    //分页
    handleSizeChange(val) {
      //每页 ${val} 条
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getData();
    },
    //查询
    search() {
      this.getData();
    },
    //新增
    handleAdd() {
      console.log(this.ruleForm.detail_images);
      this.type = "add";
      this.currentRow = {};
      this.visible = true;
    },
    //编辑
    handleEdit(row) {
      this.type = "edit";
      // this.getMenuImages(row.id);
      console.log(row);
      // this.cateSelects(row.merchant_id); //商品分类列表
      this.goodsRow = [];
      this.currentRow = row;
      this.ruleForm = {
        menu_image: row.mainPicture,
        menu_name: row.bannerName,
        inventory: row.sort,
        cate_id: row.bannerType,
        objectId: row.objectId,
      };
      let index = this.cleckData.findIndex((v2) => {
        return row.objectId == v2.id;
      });
      // 让设备反选
      if(index != -1) {
      this.goodsRow.push(this.cleckData[index]);

      }
      this.visible = true;
    },
    // 获取当前商品的图片
    getMenuImages(id) {
      let parm = {
        menu_id: id,
      };
      this.postRequest(getMenuImages, parm, MAIN).then((res) => {
        if (res.code == 200) {
          this.ruleForm.detail_images = res.data.detail_images;
          this.ruleForm.rotation_images = res.data.rotation_images;
        }
      });
    },
    goMenuSku(row) {
      this.$router.push({
        path: "/MenuSkuList",
      });
    },
    //删除
    handleDel(id) {
      let parm = {
        id: id,
        userId: this.userinfo.id,
      };
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.postRequest(bannerDel, parm, MAIN).then((res) => {
          if (res.code == 200) {
            this.$notify({
              title: "删除成功",
              message: res.msg,
              type: "success",
            });
            this.getData();
          }
        });
      }).catch(() => {});
    },

    onConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          // setTimeout(() => this.onCancel(formName), 1000);
          if (this.type == "add") {
            this.addMenu();
          } else if (this.type == "edit") {
            this.editMenu();
          }
        } else {
          return false;
        }
      });
    },
    // 添加
    addMenu() {
      if (this.goodsRow.length == 0 || this.goodsRow == "") {
        this.$notify.error("请选择一个产品");
        this.confirmLoading = false;
        return 
      }
      let params = {
        userId: this.userinfo.id,
        usageType: 2,
        bannerName: this.ruleForm.menu_name,
        mainPicture: this.ruleForm.menu_image,
        sort: this.ruleForm.inventory,
        objectId: this.goodsRow[0].id,
        bannerType: this.ruleForm.cate_id,
      };

      this.postRequest(bannerAdd, params, MAIN).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$notify({
            title: "添加成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    // 编辑
    editMenu() {
      if (this.goodsRow.length == 0 || this.goodsRow == "")
        return this.$notify.error("请选择一个产品");
      let params = {
        id: this.currentRow.id,
        userId: this.userinfo.id,
        usageType: 2,
        bannerName: this.ruleForm.menu_name,
        mainPicture: this.ruleForm.menu_image,
        sort: this.ruleForm.inventory,
        objectId: this.goodsRow[0].id,
        bannerType: this.ruleForm.cate_id,
      };

      this.postRequest(bannerEdit, params, MAIN).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$notify({
            title: "编辑成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    // 关闭弹框
    onCancel(formName) {
      this.ruleForm.rotation_images = [];
      this.ruleForm.detail_images = [];
      this.$refs[formName].resetFields();
      this.goodsRow = [];
      this.onReset();
      
      this.$refs.multipleTable.clearSelection();

    },
    // 选择产品
    clickDevic() {
      this.goodsDialog = true;
      setTimeout(() => {
        this.goodsRow.map((v) => {
          this.$refs.multipleTable.toggleRowSelection(v, true);
        });
      }, 300);
    },
    //清空重置表单
    onReset() {
      this.visible = false;
      if (this.$refs.img) this.$refs.img.clear();
      if (this.$refs.image) this.$refs.image.clear();

      if (this.$refs.editor) this.$refs.editor.clear();
      this.confirmLoading = false;
      this.ruleForm = {
        menu_name: "",
        menu_price: "",
        menu_image: "",
        is_show: 1,
        inventory: "",
        cate_id: 1,
        menu_content: "",
        rotation_images: "", //轮播图片列表 商品
        detail_images: [], //详情图片列表 商品
      };
      // this.$refs.multipleTable.toggleAllSelection(false);
    },
    // 跳转到商品的规格
    goMenuSku(row) {
      this.$router.push({
        path: "/MenuSkuList",
        query: { menu_id: row.id, merchant_id: row.merchant_id },
      });
    },
    // 下架
    goMenuTastes(row) {
      let parm = {
        id: row.id,
        isSale: row.isSale == 1 ? 2 : 1,
      };
      this.$confirm("确认修改?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.postRequest(saleUpdate, parm, MAIN).then((res) => {
          if (res.code == 200) {
            this.$notify({
              message: res.msg,
              type: "success",
            });
            this.getData();
          }
        });
      });
    },
  },
};
</script>

<style scoped>
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1890ff;
  color: #fff;
  cursor: pointer;
}
.formInput {
  width: 300px;
}
.pageBox {
  width: 100%;
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
/deep/ .el-input--mini .el-input__inner {
  height: 32px;
  line-height: 32px;
}
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
/deep/ input[type="number"] {
  -moz-appearance: textfield;
}

/deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 121px;
  height: 121px;
}
/deep/ .el-upload--picture-card {
  width: 121px;
  height: 121px;
  line-height: 130px;
}
</style>
